package cn.kimming.rpc.autoconfigure.listener;

import cn.kimming.rpc.common.exception.RpcServerException;
import cn.kimming.rpc.remoting.server.SpringBootRpcServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.ResolvableType;

public class MyRpcServerApplicationListener implements GenericApplicationListener {

    private Logger logger = LoggerFactory.getLogger(MyRpcServerApplicationListener.class);

    private static final Class<?>[] supportedTypes = new Class[]{ApplicationEnvironmentPreparedEvent.class, ApplicationStartedEvent.class};

    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        for (Class<?> supportedType : supportedTypes) {
            if (supportedType.isAssignableFrom(eventType.getRawClass())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return true;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
         if (event instanceof ApplicationStartedEvent) {
            onApplicationStarted((ApplicationStartedEvent)event);
        }
    }


    private void onApplicationStarted(ApplicationStartedEvent event) {
        logger.info("[my-rpc] ApplicationStarted: 准备启动rpc server");
        ConfigurableApplicationContext applicationContext = event.getApplicationContext();

        SpringBootRpcServer newRpcServer = new SpringBootRpcServer(applicationContext);
        try {
            newRpcServer.start();
        } catch (Exception e) {
            logger.error("[my-rpc] start rpc server failed", e);
            throw new RpcServerException("start rpc server failed");
        }

    }
}
